package models

import (
	"fmt"
	"time"
)

// [TODO] 事实上,本项目下models定义下的结构体中的json标签是多余的,因为与前端交互的对象存在dto目录下
type Account struct {
	ID          uint      `gorm:"primaryKey" json:"id"`
	AccountNo   string    `gorm:"size:64;uniqueIndex" json:"account_no"`
	OwnerUserID uint      `gorm:"not null;index" json:"owner_user_id"`
	Balance     float64   `gorm:"type:decimal(18,2);default:0" json:"balance"`
	Status      string    `gorm:"type:enum('active','frozen','closed');default:'active'" json:"status"`
	CreatedTime time.Time `gorm:"autoCreateTime" json:"created_time"`
	UpdateTime  time.Time `gorm:"autoUpdateTime" json:"update_time"`
}

// GetAccountByUserID 获取某用户的账户
func GetAccountByUserID(userID uint) (*Account, error) {
	var account Account
	if err := DB.Where("owner_user_id = ?", userID).First(&account).Error; err != nil {
		return nil, err
	}
	return &account, nil
}

// GetAllAccounts 获取所有账户（可供出纳员/审计员使用）
func GetAllAccounts() ([]Account, error) {
	var accounts []Account
	if err := DB.Find(&accounts).Error; err != nil {
		return nil, err
	}
	return accounts, nil
}

func GenerateAccountNo() string {
	return fmt.Sprintf("%d", time.Now().UnixNano())
}

func CreateAccount(account *Account) error {
	if account.AccountNo == "" {
		account.AccountNo = GenerateAccountNo()
	}
	return DB.Create(account).Error
}

func CreateUser(user *User) error {
	return DB.Create(user).Error
}

func UpdateAccountStatus(accountID uint, status string) error {
	return DB.Model(&Account{}).
		Where("id = ?", accountID).
		Update("status", status).Error
}
